<?php

namespace yan\googlebusiness\factory;

use Exception;

class ShoppingContent extends \yan\googlebusiness\AbstractFactory
{
    const BATCH_SIZE = 10;

    public function list()
    {
        $parameters = ['maxResults' => self::BATCH_SIZE - 1];
        $products = $this->getService()->getShoppingContent()->products->listProducts(
            $this->getService()->getAttr('merchantId'),
            $parameters
        );
        $count = 0;
        // You can fetch all items in a loop. We limit to looping just 3
        // times for this example as it may take a long time to finish if you
        // already have many products.
        $list = [];
        while (!empty($products->getResources()) && $count++ < 3) {
            foreach ($products->getResources() as $product) {
                // printf("%s %s\n", $product->getId(), $product->getTitle());
                $list[$product->getId()] = $product;
            }
            // If the result has a nextPageToken property then there are more pages
            // available to fetch
            if (empty($products->getNextPageToken())) {
                break;
            }
            // You can fetch the next page of results by setting the pageToken
            // parameter with the value of nextPageToken from the previous result.
            $parameters['pageToken'] = $products->nextPageToken;
            $products = $this->getService()->getShoppingContent()->products->listProducts(
                $this->getService()->getAttr('merchantId'),
                $parameters
            );
        }
        return $list;
    }
    public function add($data)
    {
        $product = $this->buildProductModel($data);

        $result = $this->getService()->getShoppingContent()->products->insert($this->getService()->getAttr('merchantId'), $product);
        return $result;
    }
    public function update($data)
    {
        return $this->add($data);
    }
    public function delete($offerId)
    {
        $productId = $this->buildProductId($offerId);
        // The response for a successful delete is empty
        $this->getService()->getShoppingContent()->products->delete(
            $this->getService()->getAttr('merchantId'),
            $productId
        );
    }
    public function getProduct($offerId)
    {
        $productId = $this->buildProductId($offerId);
        $product = $this->getService()->getShoppingContent()->products->get(
            $this->getService()->getAttr('merchantId'),
            $productId
        );
        return $product;
    }
    private function buildProductId($offerId)
    {
        return sprintf(
            '%s:%s:%s:%s',
            \yan\googlebusiness\model\Product::CHANNEL,
            \yan\googlebusiness\model\Product::CONTENT_LANGUAGE,
            \yan\googlebusiness\model\Product::TARGET_COUNTRY,
            $offerId
        );
    }

    public function insertProductBatch($products)
    {
        $entries = [];
        $messages = [];
        foreach ($products as $key => $val) {
            
            $product = $this->buildProductModel($val);
            $entry =
                new \Google\Service\ShoppingContent\ProductsCustomBatchRequestEntry();
            $entry->setMethod('insert');
            $entry->setBatchId($key);
            $entry->setProduct($product);
            $entry->setMerchantId($this->getService()->getAttr('merchantId'));

            $entries[] = $entry;
        }

        $batchRequest =
            new \Google\Service\ShoppingContent\ProductsCustomBatchRequest();
        $batchRequest->setEntries($entries);

        $batchResponse =
        $this->getService()->getShoppingContent()->products->custombatch($batchRequest);

        $messages[] = sprintf("Inserted %d products.\n", count($batchResponse->entries));

        foreach ($batchResponse->entries as $entry) {
            if (empty($entry->getErrors())) {
                $product = $entry->getProduct();
            } else {
                $messages[] = sprintf("There were errors inserting a product:\n");
                foreach ($entry->getErrors()->getErrors() as $error) {
                    $messages[] = sprintf("\t%s\n", $error->getMessage());
                }
            }
        }
        return $messages;
    }
    public function deleteProductBatch($offerIds) {
        $entries = [];
    
        foreach ($offerIds as $key => $offerId) {
          $entry =
              new \Google\Service\ShoppingContent\ProductsCustomBatchRequestEntry();
          $entry->setMethod('delete');
          $entry->setBatchId($key);
          $entry->setProductId($this->buildProductId($offerId));
          $entry->setMerchantId($this->getService()->getAttr('merchantId'));
    
          $entries[] = $entry;
        }
    
        $batchRequest =
            new \Google\Service\ShoppingContent\ProductsCustomBatchRequest();
        $batchRequest->setEntries($entries);
    
        $batchResponses =
            $this->getService()->getShoppingContent()->products->custombatch($batchRequest);
        $errors = 0;
        foreach ($batchResponses->entries as $entry) {
          if (!empty($entry->getErrors())) {
            $errors++;
          }
        }
        $message = [];
        $message[] = "Requested delete of batch inserted test products\n";
        $message[] = sprintf("There were %d errors\n", $errors);
        return $message;
      }
    public function buildProductModel($data){
        $product = new \Google\Service\ShoppingContent\Product();
        $product->setOfferId($data['offerId']);
        $product->setTitle($data['title']);
        $product->setDescription($data['description']);
        $product->setLink($data['link']);
        $product->setImageLink($data['image_link']);
        $product->setContentLanguage($data['content_language']);
        $product->setTargetCountry($data['target_country']);
        $product->setChannel($data['channel']);
        $product->setAvailability('in stock');
        $product->setCondition($data['condition']);
        $product->setGtin($data['gtin']);

        $price = new \Google\Service\ShoppingContent\Price();
        $priceArr = explode(' ', $data['price']);
        $price->setValue($priceArr['0']);
        $price->setCurrency($priceArr['1']);

        $product->setPrice($price);
        return $product;
    }
}
